package com.chenjt.jvm.second.three_instruct;

/**
 * 注释：
 *
 * 指令3：类型转换指令
 *
 * @author chenjt
 * @date 2025/6/27 14:27
 */
public class ClassCastTest {

    // 宽化类型转换
    public static void main(String[] args) {
//        upCast2();
        downCast5();
    }


    // 针对于宽化类型转换的基本测试
    public static void upCast1(){
        int i = 10;
        long l = i;
        float f = i;
        double d = i;

        float f1 = l;
        double d1 = l;
        double d2 = f1;
    }


    // 举例：精度损失的问题
    public static void upCast2(){
        int i = 123123123;
        float f = i;
        System.out.println(f);// 1.2312312E8（发现已经发生了精度损失了）

        long l = 123123123123L; // 1.23123123123E11（该数值没有发生精度损失）
        l = 123123123123123123L;// 1.2312312312312312E17（该数值发生精度损失）
        double d = l;
        System.out.println(d);
    }


    // 针对byte、short等转换为容量大的类型时，将此类型看作int类型处理
    public static void upCast3(byte b){
        int i = b;
        long l = b;
        double d = b;
    }


    public void upCast4(short s){
        int i = s;
        long l = s;
        double f = s;
    }


    // 窄化类型转换
    // 基本使用
    public void downCast1(){
        int i = 10;
        byte b = (byte)i;
        short s = (short)i;
        char c = (char)i;

        long l = 10L;
        int i1 = (int)l;
        byte b1 = (byte)l;
    }

    public void downCast2(){
        float f = 10;
        long l = (long)f;
        int i = (int)f;
        byte b = (byte)f;

        double d = 10;
        byte b1 = (byte)d;
    }

    public void downCast3(){
        short s = 10;
        byte b = (byte)s;
    }

    // 窄化类型转换的精度损失
    public void downCast4(){
        int i = 128;
        byte b = (byte)i;
        System.out.println(b);// -128
    }

    // 测试NaN，无穷大的情况
    public static void downCast5(){
        double d1 = Double.NaN;// 0.0 / 0.0
        int i = (int)d1;
        System.out.println(i);// 0

        double d2 = Double.POSITIVE_INFINITY;// 1.0 / 0.0（正无穷大）
        long l = (long)d2;
        int j = (int)d2;
        System.out.println(l);// Long.MAX_VALUE
//        System.out.println(Long.MAX_VALUE);
        System.out.println(j);// Integer.MAX_VALUE
//        System.out.println(Integer.MAX_VALUE);

        float f = (float)d1;
        System.out.println(f);// NaN
    }

}
